package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.base.ResponseResult;
import com.crm.domain.dto.AssignmentDto;
import com.crm.domain.entity.Assignment;
import com.crm.domain.entity.Business;
import com.crm.domain.entity.BusinessPool;
import com.crm.domain.query.BusinessQuery;
import com.crm.mapper.AssignmentMapper;
import com.crm.mapper.BusinessMapper;
import com.crm.mapper.BusinessPoolMapper;
import com.crm.mapper.UserMapper;
import com.crm.service.IBusinessPoolService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 公海池表 服务实现类
 * </p>
 *
 * @author Hulunico
 * @since 2024-08-08
 */
@Service
@RequiredArgsConstructor
public class BusinessPoolServiceImpl extends ServiceImpl<BusinessPoolMapper, BusinessPool> implements IBusinessPoolService {
    @Override
    public Page<BusinessPool> getList(BusinessQuery query) {
        Page<BusinessPool> page = new Page<>(query.getPageNum(), query.getPageSize());

        LambdaQueryWrapper<BusinessPool> wrapper = Wrappers.<BusinessPool>lambdaQuery()
                .eq(ObjectUtil.isNotNull(query.getId()), BusinessPool::getId, query.getId())
                .like(ObjectUtil.isNotNull(query.getName()), BusinessPool::getName, query.getName())
                .like(ObjectUtil.isNotNull(query.getPhone()), BusinessPool::getPhone, query.getPhone())
                .eq(ObjectUtil.isNotNull(query.getSubject()), BusinessPool::getSubject, query.getSubject())

                .between(ObjectUtil.isNotNull(query.getBeginCreateTime()) && ObjectUtil.isNotNull(query.getEndCreateTime()),
                        BusinessPool::getCreateTime, query.getBeginCreateTime(), query.getEndCreateTime());
        Page<BusinessPool> businessPoolPage = page(page, wrapper);
        return businessPoolPage;
    }

    private final BusinessPoolMapper businessPoolMapper;
    private final AssignmentMapper assignmentMapper;
    private final BusinessMapper businessMapper;
    private final UserMapper userMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult gain(AssignmentDto dto) {

        // 1.查询公海池记录:根据提供的 ID 列表查询公海池中的记录。
        List<Long> ids = dto.getIds();
        List<BusinessPool> businessPools = businessPoolMapper.selectBatchIds(ids);

        //2.检查用户已有商机数量
         Integer count=assignmentMapper.countBusiness(dto.getUserId());
         if (count>=100){
             return ResponseResult.error("操作失败，您的商机保有量已达到上限");
         }


         //3.创建分配记录 为每个需要转移的商机创建一条分配记录
        dto.getIds().forEach(id->{
            Assignment assignment=new Assignment();
            assignment.setBusinessId(id)
                    .setUserId(dto.getUserId())
                    .setCreateTime(LocalDateTime.now())
                    .setUpdateTime(LocalDateTime.now());
           assignmentMapper.insert(assignment);
        });
         //4.复制记录到业务表 将公海池中的商机记录复制到业务表中。
        businessPools.forEach(businessPool -> {
            Business business = BeanUtil.copyProperties(businessPool, Business.class);
            business.setOwner(userMapper.selectById(dto.getUserId()).getUserName());
            business.setCreateTime(LocalDateTime.now());
            businessMapper.insert(business);
        });
         //删除公海池记录
        businessPoolMapper.deleteBatchIds(ids);
        return ResponseResult.success();

    }
}
